Skip to main content

Relationships between Go types and JSON

A basic principle of the integration between Go and ArangoDB is the mapping from Go types to JSON documents. Data in the database map to types in Go through JSON. You will need at least two types in a Golang program to work with graphs

Go uses a special syntax to map values like struct members like Key, Weight, Data, etc., into JSON fields. Remember that member names should start with a capital letter to be accessible outside a packaged scope. You declare types and their JSON mappings once, as in the examples below.

// A typical document type

type IntKeyValue struct {

Key string `json:"_key"` // mandatory field (handle) - short name
Value int `json:"value"`
}

// A typical vertex type must have field matching _key

type MyVertexNode struct {

Key string `json:"_key"` // mandatory field (handle) - short name

// other fields … e.g.

Data string `json: "data"` // Longer description or bulk string data
Weight float64 `json:"weight"` // importance rank
}

// A typical edge type must have fields matching _from and _to

type MyEdgeLink struct {

Key string `json:"_key"` // mandatory field (handle)
From string `json:"_from"` // mandatory field
To string `json:"_to"` // mandatory field

// other fields … e.g.

Weight float64 `json:"weight"`

}

When reading data from ArangoDB with, say, ReadDocument(), the API asks you to submit a variable of some type, say MyDocumentType, by reference using the & operator:

 var variable MyDocumentType
mycollection.ReadDocument(nil, rawkey, &variable)

This submitted type is not necessarily a fixed type, but it must be a type whose members map (at least partially) to the named fields in the database’s JSON document representation. Only matching fields will be filled in. This means you could create several different Go types to read the same documents in the database, as long as they have some type fields that match JSON fields. In other words, the mapping need not be unique or one-to-one, so there is great flexibility in making new types to extract a subset of the fields in a document.

The document model in ArangoDB does not require all documents in a collection to have the same fields. You can choose to have ad hoc schemas and extract only a consistent set of fields in a query, or rigidly check that all documents have the same schema. This is a user choice.

 
Help us improve

Anything unclear or buggy in this tutorial? Provide Feedback